package com.syyo.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syyo.common.constant.AuthConstant;
import com.syyo.common.domain.ResultVo;
import com.syyo.common.enums.ResultEnum;
import com.syyo.common.exception.SysException;
import com.syyo.common.to.mq.OrderTo;
import com.syyo.common.to.mq.SeckillOrderTo;
import com.syyo.common.utils.MyHttpUtils;
import com.syyo.common.utils.MyJSONUtils;
import com.syyo.common.vo.MemberVo;
import com.syyo.common.vo.SkuHasStockVo;
import com.syyo.gulimall.order.config.rabbit.MyMQConfig;
import com.syyo.gulimall.order.constant.OrderConstant;
import com.syyo.gulimall.order.domain.entity.OrderEntity;
import com.syyo.gulimall.order.domain.entity.OrderItemEntity;
import com.syyo.gulimall.order.domain.entity.PaymentInfoEntity;
import com.syyo.gulimall.order.domain.req.OrderReq;
import com.syyo.gulimall.order.domain.to.OderCreateTo;
import com.syyo.gulimall.order.domain.vo.*;
import com.syyo.gulimall.order.enume.OrderStatusEnum;
import com.syyo.gulimall.order.feign.CartFeign;
import com.syyo.gulimall.order.feign.MemberFeign;
import com.syyo.gulimall.order.feign.ProductFeign;
import com.syyo.gulimall.order.feign.WareFeign;
import com.syyo.gulimall.order.interceptor.LoginUserInterceptor;
import com.syyo.gulimall.order.mapper.OrderItemMapper;
import com.syyo.gulimall.order.mapper.OrderMapper;
import com.syyo.gulimall.order.mapper.PaymentInfoMapper;
import com.syyo.gulimall.order.service.OrderItemService;
import com.syyo.gulimall.order.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

//import io.seata.spring.annotation.GlobalTransactional;


/**
 * 订单
 *
 * @author syyo
 * @email syyo@gmail.com
 * @date 2021-01-20 10:01:14
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderEntity> implements OrderService {


    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private MemberFeign memberFeign;

    @Autowired
    CartFeign cartFeign;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    WareFeign wareFeign;

    @Autowired
    ProductFeign productFeign;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    HttpServletRequest request;

    @Autowired
    PaymentInfoMapper paymentInfoMapper;

    /**
     * 新增
     */
    @Override
    @Transactional
    public int add(OrderReq req) {
        OrderEntity entity = new OrderEntity();
        // 添加创建时间和更新时间
        BeanUtils.copyProperties(req, entity);
        int insert = orderMapper.insert(entity);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_10001.getCode(), ResultEnum.E_10001.getMessage());
        }
        return insert;
    }

    /**
     * 删除
     */
    @Override
    @Transactional
    public int del(Integer id) {
        int insert = orderMapper.deleteById(id);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_10002.getCode(), ResultEnum.E_10002.getMessage());
        }
        return insert;
    }

    /**
     * 编辑
     */
    @Override
    @Transactional
    public int edit(OrderReq req) {
        OrderEntity entity = new OrderEntity();
        // 添加更新时间
        BeanUtils.copyProperties(req, entity);
        int insert = orderMapper.updateById(entity);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_10003.getCode(), ResultEnum.E_10003.getMessage());
        }
        return insert;
    }

    /**
     * 详情
     */
    @Override
    public OrderEntity findOne(Integer id) {
        return orderMapper.selectById(id);
    }

    /**
     * 列表
     */
    @Override
    public IPage<OrderEntity> findAll(Integer pageNum, Integer pageSize, OrderReq req) {
        Page<OrderEntity> teacherPage = new Page<OrderEntity>(pageNum, pageSize);
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        return orderMapper.selectPage(teacherPage, wrapper);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();

        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        // 从主线程拿到存储的数据，再存入子线程中，完成线程间的数据共享
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();


        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            // 远程查询所有的收货地址
            // 存入子线程中
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> memberAddressVos = memberFeign.listAddress(memberVo.getId());
            orderConfirmVo.setAddressVoList(memberAddressVos);
        }, executor);


        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            // 远程查询购物车所有选中的购物项
            // 存入子线程中
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> currentUserCartItems = cartFeign.getCurrentUserCartItems();
            orderConfirmVo.setItemVos(currentUserCartItems);
        }, executor).thenRunAsync(() -> {
            // 查询库存信息
            List<OrderItemVo> itemVos = orderConfirmVo.getItemVos();
            List<Long> collect = itemVos.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());

            List<SkuHasStockVo> skuHasStock = wareFeign.findSkuHasStock(collect);
            if (skuHasStock != null) {
                Map<Long, Boolean> map = skuHasStock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        }, executor);

//        // 远程查询所有的收货地址
//        List<MemberAddressVo> memberAddressVos = memberFeign.listAddress(memberVo.getId());
//        orderConfirmVo.setAddressVoList(memberAddressVos);
//
//        // 远程查询购物车所有选中的购物项
//        List<OderItemVo> currentUserCartItems = cartFeign.getCurrentUserCartItems();
//        orderConfirmVo.setItemVos(currentUserCartItems);

        // 查询用户积分
        Integer integration = orderConfirmVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        // todo 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        orderConfirmVo.setOrderToke(token);
        // 设置过期时间必须和加锁是原子操作
//        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId(), token, 30, TimeUnit.MINUTES);

        CompletableFuture.allOf(addressFuture, cartFuture).get();
        return orderConfirmVo;
    }

    /**
     * 事物
     * 传播行为
     * Propagation
     * REQUIRED  共用一个事物
     * REQUIRES_NEW 使用一个新的事物
     * <p>
     * 同一个对象的事物方法，默认是用第一次的事物方法，其他事物方法会失效，原因绕过了代理对象
     */

    @Transactional
    public void a() { //a事物
//        b();//a事物
//        c();//新的事物（不回滚）

        OrderServiceImpl proxy = (OrderServiceImpl) AopContext.currentProxy();

        proxy.b();// 使用代理对象调用，b() c()方法的事物设置才生效
        proxy.c();
        int i = 10 / 0;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void b() {
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void c() {
    }

    /**
     * 分布式锁
     */
//    @GlobalTransactional
    @Transactional
    @Override
    public OrderSubmitRespVo submitOrder(OrderSubmitVo vo) {
        OrderSubmitRespVo respVo = new OrderSubmitRespVo();
        respVo.setCode(0);
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        confirmVoThreadLocal.set(vo);


        String redisKey = OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId();
        // 验证令牌【令牌的比较和删除是原子性操作】
        String orderToken = vo.getOrderToken();
        // 原子性, 使用lua脚本解锁
        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        // 原子删锁
        Long lock = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(redisKey), orderToken);
        if (lock == 0L) {
            // 令牌验证失败
            respVo.setCode(1);
            return respVo;
        } else {
            // 令牌验证通过
            // 下单，创建订单，验价格，锁库存

            // 1.创建订单
            OderCreateTo order = createOrder();

            // 2.验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) > 0.01) {
                // 金额对比失败
                respVo.setCode(2);
                return respVo;
            } else {
                // 成功
                // 3.保存订单
                saveOrder(order);

                // 4.库存锁定,只要有异常，回滚
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());

                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());

                    return orderItemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                // todo 远程锁库存
                ResultVo wareResp = wareFeign.orderLockStock(lockVo);
                if (wareResp.getCode() == 20000) {
                    // 订单创建成功
                    respVo.setOrder(order.getOrder());
//                    int i = 1/0;
                    // todo 订单发送给延迟队列
                    rabbitTemplate.convertAndSend(MyMQConfig.ORDER_EXCHANGE, MyMQConfig.ORDER_CREATE_ORDER, order.getOrder());
                    return respVo;
                } else {
                    // 失败
                    respVo.setCode(3);
                    return respVo;
                }
            }
        }
        // 不是原子性
//        String redisToken = redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId());
//        if (orderToken != null && orderToken.equals(redisToken)){
//            // 令牌验证通过
//            redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberVo.getId());
//        }
    }

    @Override
    public OrderEntity getOrderStatus(String orderSn) {
        return orderMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    /**
     * 关闭订单
     *
     * @param order
     */
    @Override
    public void closeOrder(OrderEntity order) {
        // 查询当前订单的状态
//        OrderEntity orderEntity = this.getById(order.getOrderSn());
        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().
                eq("order_sn",order.getOrderSn()));
        if (orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            // 关单
            OrderEntity newOrder = new OrderEntity();
            newOrder.setStatus(OrderStatusEnum.CANCLED.getCode());
            newOrder.setId(orderEntity.getId());
            this.updateById(newOrder);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            // 解锁成功，给库存服务发送解锁库存的消息
            try{
                // 保证消息一定发送出去，每发一次消息做一个日志记录，定期扫描数据库，将失败的消息在发一遍
                rabbitTemplate.convertAndSend(MyMQConfig.ORDER_EXCHANGE, MyMQConfig.ORDER_MATCH_OTHER, orderTo);
            }catch (Exception e){
                //
            }

        }
    }

    /**
     * 获取当前订单的支付信息
     * @param orderSn
     * @return
     */
    @Override
    public PayVo getOrderPay(String orderSn) {

        OrderEntity order = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn",orderSn));
        OrderItemEntity orderItem = orderItemMapper.selectOne(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        BigDecimal bigDecimal = order.getPayAmount().setScale(2,BigDecimal.ROUND_UP);
        PayVo payVo = new PayVo();
        payVo.setBody(orderItem.getSkuAttrsVals());//订单备注
        payVo.setSubject(orderItem.getSkuName());//订单主题
        payVo.setOut_trade_no(orderSn);//订单号
        payVo.setTotal_amount(bigDecimal.toString());//订单金额
        return payVo;
    }

    /**
     * 分页 查询当前登录用户的所有订单
     * @param pageNum
     * @param pageSize
     * @param
     * @return
     */
    @Override
    public IPage<OrderEntity> listWithItem(Integer pageNum, Integer pageSize, Map<String,Object> params) {
        MemberVo memberVo = (MemberVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER);
        Page<OrderEntity> teacherPage = new Page<OrderEntity>(pageNum, pageSize);
        QueryWrapper<OrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id",memberVo.getId());
        wrapper.orderByDesc("id");
        IPage<OrderEntity> list = orderMapper.selectPage(teacherPage, wrapper);

        List<OrderEntity> order_sn = list.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemMapper.selectList(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setOrderItemEntityList(itemEntities);
            return order;
        }).collect(Collectors.toList());
        list.setRecords(order_sn);
        return list;
    }

    /**
     * 处理支付宝的返回结果
     * @param vo
     * @return
     */
    @Override
    public String handleAliPay(PayAsyncVo vo) {
        //1.保存交易流水

        //保存交易流水信息
        PaymentInfoEntity paymentInfo = new PaymentInfoEntity();
        paymentInfo.setOrderSn(vo.getOut_trade_no());
        paymentInfo.setAlipayTradeNo(vo.getTrade_no());
        paymentInfo.setTotalAmount(new BigDecimal(vo.getBuyer_pay_amount()));
        paymentInfo.setSubject(vo.getBody());
        paymentInfo.setPaymentStatus(vo.getTrade_status());
        paymentInfo.setCreateTime(new Date());
        paymentInfo.setCallbackTime(vo.getNotify_time());
        paymentInfoMapper.insert(paymentInfo);

        //2.修改订单状态
        String tradeStatus = vo.getTrade_status();
        if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
            //支付成功状态
            String orderSn = vo.getOut_trade_no(); //获取订单号
            orderMapper.updateOrderStatus(orderSn,OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    /**
     * 创建秒杀订单
     * @param
     */
    @Override
    public void createSeckillOrder(SeckillOrderTo orderTo) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(orderTo.getOrderSn());
        orderEntity.setMemberId(orderTo.getMemberId());
        orderEntity.setCreateTime(new Date());
        BigDecimal totalPrice = orderTo.getSeckillPrice().multiply(BigDecimal.valueOf(orderTo.getNum()));
        orderEntity.setPayAmount(totalPrice);
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        //保存订单
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItem = new OrderItemEntity();
        orderItem.setOrderSn(orderTo.getOrderSn());
        orderItem.setRealAmount(totalPrice);

        orderItem.setSkuQuantity(orderTo.getNum());

        //保存商品的spu信息
//        R spuInfo = productFeignService.getSpuInfoBySkuId(orderTo.getSkuId());
//        SpuInfoVo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoVo>() {
//        });
//        orderItem.setSpuId(spuInfoData.getId());
//        orderItem.setSpuName(spuInfoData.getSpuName());
//        orderItem.setSpuBrand(spuInfoData.getBrandName());
//        orderItem.setCategoryId(spuInfoData.getCatalogId());

        //保存订单项数据
        orderItemService.save(orderItem);
    }


    /**
     * 保存订单
     *
     * @param order
     */
    private void saveOrder(OderCreateTo order) {
        // 保存订单
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        int insert = orderMapper.insert(orderEntity);

        // 保存订单项
        List<OrderItemEntity> orderItems = order.getOrderItems();
        for (OrderItemEntity orderItem : orderItems) {
            orderItemMapper.insert(orderItem);
        }
        // 使用seata的数据源代理mybaties-plus的数据，批量插入会报错，所以改成不用批量，或者自定义批量sql
//        orderItemService.saveBatch(orderItems);
    }


    private OderCreateTo createOrder() {
        OderCreateTo oderCreateTo = new OderCreateTo();
        // 1.生成订单号
        String orderSn = IdWorker.getTimeId();

        OrderEntity orderEntity = buildOrder(orderSn);

        // 2.获取所有的购物项
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

        // 3.计算价格
        computPrice(orderEntity, itemEntities);

        oderCreateTo.setOrder(orderEntity);
        oderCreateTo.setOrderItems(itemEntities);
        return oderCreateTo;
    }

    /**
     * 计算价格
     *
     * @param order
     * @param orderItems
     */
    private void computPrice(OrderEntity order, List<OrderItemEntity> orderItems) {

        BigDecimal total = new BigDecimal("0.0");// 总价
        BigDecimal coupon = new BigDecimal("0.0");// 优惠券优惠价
        BigDecimal promotion = new BigDecimal("0.0");//促销价
        BigDecimal integration = new BigDecimal("0.0");// 积分优惠价


        BigDecimal gift = new BigDecimal("0.0");// 总积分
        BigDecimal growth = new BigDecimal("0.0");// 成长值
        // 1.订单价格,叠加每一个商品的总价
        for (OrderItemEntity orderItem : orderItems) {

            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            integration = integration.add(orderItem.getIntegrationAmount());
            total = total.add(orderItem.getRealAmount());

            gift = gift.add(new BigDecimal(orderItem.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(orderItem.getGiftGrowth().toString()));
        }
        // 设置价格相关
        order.setTotalAmount(total); // 总额
        order.setPayAmount(total.add(order.getFreightAmount())); // 应付总额
        order.setCouponAmount(coupon);
        order.setPromotionAmount(promotion);
        order.setIntegrationAmount(integration);

        // 设置成长值
        order.setIntegration(gift.intValue());
        order.setGrowth(growth.intValue());

        order.setDeleteStatus(0);// 默认未删除
    }

    /**
     * 构建订单
     *
     * @param orderSn
     */
    private OrderEntity buildOrder(String orderSn) {
        // 从拦截器拿会员信息
        MemberVo memberVo = LoginUserInterceptor.loginUser.get();
        OrderEntity order = new OrderEntity();
        order.setOrderSn(orderSn);
        order.setMemberId(memberVo.getId());
        // 获取收货地址信息
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        ResultVo fare = wareFeign.getFare(orderSubmitVo.getAddrId());
        Object data = fare.getData();

        FareVo fareVo = MyJSONUtils.typeCast(new TypeReference<FareVo>() {
        }, data);
        // 设置运费
        order.setFreightAmount(fareVo.getFare());
        // 设置收货人
        order.setReceiverCity(fareVo.getAddress().getCity());
        order.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        order.setReceiverName(fareVo.getAddress().getName());
        order.setReceiverPhone(fareVo.getAddress().getPhone());
        order.setReceiverPostCode(fareVo.getAddress().getPostCode());
        order.setReceiverRegion(fareVo.getAddress().getRegion());

        // 设置订单状态
        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        order.setAutoConfirmDay(7);
        return order;
    }

    /**
     * 构建所有的订单项数据
     *
     * @param
     * @return
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 最后确定每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeign.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(item -> {
                OrderItemEntity orderItemEntity = buildOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;

    }

    /**
     * 构建每一个订单项数据
     *
     * @param
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity orderItem = new OrderItemEntity();
        // 1.订单信息
        // 2.商品的spu信息
        Long skuId = item.getSkuId();
        ResultVo spu = productFeign.getSpuBySkuId(skuId);
        SpuInfoVo spuInfoVo = MyJSONUtils.typeCast(new TypeReference<SpuInfoVo>() {
        }, spu.getData());
        orderItem.setSpuId(spuInfoVo.getId());
        orderItem.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItem.setSpuName(spuInfoVo.getSpuName());
        orderItem.setCategoryId(spuInfoVo.getCatalogId());


        // 3.商品的sku信息
        orderItem.setSkuId(item.getSkuId());
        orderItem.setSkuName(item.getTitle());
        orderItem.setSkuPic(item.getImage());
        orderItem.setSkuPrice(item.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(item.getSkuAttr(), ";");
        orderItem.setSkuAttrsVals(skuAttr);
        orderItem.setSkuQuantity(item.getCount());

        // 4.优惠信息（不做）

        // 5.积分信息
        orderItem.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount())).intValue());
        orderItem.setGiftIntegration(item.getPrice().intValue());

        // 6.价格信息
        orderItem.setPromotionAmount(new BigDecimal("0"));
        orderItem.setCouponAmount(new BigDecimal("0"));
        orderItem.setIntegrationAmount(new BigDecimal("0"));

        // 当前项的实际金额 = 总金额 - 各种优惠
        BigDecimal orign = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuQuantity().toString()));
        BigDecimal subtract = orign.subtract(orderItem.getPromotionAmount())
                .subtract(orderItem.getCouponAmount())
                .subtract(orderItem.getIntegrationAmount());

        orderItem.setRealAmount(subtract);
        return orderItem;

    }

}